<!DOCTYPE html>
<html lang="zh-Hans">
<head>

    <!--[if lt IE 9]>
        <style>body {display: none; background: none !important} </style>
        <meta http-equiv="Refresh" Content="0; url=//outdatedbrowser.com/" />
    <![endif]-->

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta name="format-detection" content="telephone=no" />
<meta name="author" content="HatBoy" />



<meta name="description" content="深入Cython">
<meta name="keywords" content="Python,Cython">
<meta property="og:type" content="article">
<meta property="og:title" content="第三章 深入Cython">
<meta property="og:url" content="http://hatboy.gitee.io/2017/07/17/第三章-深入Cython/index.html">
<meta property="og:site_name" content="HatBoy的个人主页">
<meta property="og:description" content="深入Cython">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://hatboy.gitee.io/2017/07/17/第三章-深入Cython/1.png">
<meta property="og:image" content="http://hatboy.gitee.io/2017/07/17/第三章-深入Cython/2.png">
<meta property="og:updated_time" content="2017-12-21T10:08:24.881Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="第三章 深入Cython">
<meta name="twitter:description" content="深入Cython">
<meta name="twitter:image" content="http://hatboy.gitee.io/2017/07/17/第三章-深入Cython/1.png">

<link rel="apple-touch-icon" href= "/apple-touch-icon.png">


    <link rel="alternate" href="/atom.xml" title="HatBoy的个人主页" type="application/atom+xml">



    <link rel="shortcut icon" href="/img/favicon.ico">



    <link href="//cdn.bootcss.com/animate.css/3.5.1/animate.min.css" rel="stylesheet">



    <link href="//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet">



    <script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
    <link href="//cdn.bootcss.com/pace/1.0.2/themes/blue/pace-theme-minimal.css" rel="stylesheet">


<link rel="stylesheet" href="/css/style.css">



<link href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">


<title>第三章 深入Cython | HatBoy的个人主页</title>

<script src="//cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>

<script>
    var yiliaConfig = {
        fancybox: true,
        animate: true,
        isHome: false,
        isPost: true,
        isArchive: false,
        isTag: false,
        isCategory: false,
        fancybox_js: "//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.js",
        scrollreveal: "//cdn.bootcss.com/scrollReveal.js/3.1.4/scrollreveal.min.js",
        search: true
    }
</script>


    <script>
        yiliaConfig.jquery_ui = [true, "//cdn.bootcss.com/jqueryui/1.10.4/jquery-ui.min.js", "//cdn.bootcss.com/jqueryui/1.10.4/css/jquery-ui.min.css"];
    </script>



    <script> yiliaConfig.rootUrl = "\/";</script>





    <script>
        var _hmt = _hmt || [];
        (function() {
            var hm = document.createElement("script");
            hm.src = "//hm.baidu.com/hm.js?04d04bb57e5c5eaf49059aa602440263";
            var s = document.getElementsByTagName("script")[0]; 
            s.parentNode.insertBefore(hm, s);
        })();
    </script>


</head>
<body>
  <div id="container">
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
    <header id="header" class="inner">
        <a href="/" class="profilepic">
            <img src="/img/avatar.jpg" class="animated zoomIn">
        </a>
        <hgroup>
          <h1 class="header-author"><a href="/">HatBoy</a></h1>
        </hgroup>

        

        
            <form id="search-form">
            <input type="text" id="local-search-input" name="q" placeholder="search..." class="search form-control" autocomplete="off" autocorrect="off" searchonload="true" />
            <i class="fa fa-times" onclick="resetSearch()"></i>
            </form>
            <div id="local-search-result"></div>
            <p class='no-result'>No results found <i class='fa fa-spinner fa-pulse'></i></p>
        


        
            <div id="switch-btn" class="switch-btn">
                <div class="icon">
                    <div class="icon-ctn">
                        <div class="icon-wrap icon-house" data-idx="0">
                            <div class="birdhouse"></div>
                            <div class="birdhouse_holes"></div>
                        </div>
                        <div class="icon-wrap icon-ribbon hide" data-idx="1">
                            <div class="ribbon"></div>
                        </div>
                        
                        <div class="icon-wrap icon-link hide" data-idx="2">
                            <div class="loopback_l"></div>
                            <div class="loopback_r"></div>
                        </div>
                        
                        
                        <div class="icon-wrap icon-me hide" data-idx="3">
                            <div class="user"></div>
                            <div class="shoulder"></div>
                        </div>
                        
                    </div>
                    
                </div>
                <div class="tips-box hide">
                    <div class="tips-arrow"></div>
                    <ul class="tips-inner">
                        <li>菜单</li>
                        <li>标签</li>
                        
                        <li>友情链接</li>
                        
                        
                        <li>关于我</li>
                        
                    </ul>
                </div>
            </div>
        

        <div id="switch-area" class="switch-area">
            <div class="switch-wrap">
                <section class="switch-part switch-part1">
                    <nav class="header-menu">
                        <ul>
                        
                            <li><a href="/">主页</a></li>
                        
                            <li><a href="/archives/">所有文章</a></li>
                        
                            <li><a href="/tags/">标签云</a></li>
                        
                            <li><a href="/about/">关于我</a></li>
                        
                        </ul>
                    </nav>
                    <nav class="header-nav">
                        <ul class="social">
                            
                                <a class="fa Email" href="mailto:hatboy-dj@qq.com" title="Email"></a>
                            
                                <a class="fa GitHub" href="https://github.com/HatBoy/" title="GitHub"></a>
                            
                                <a class="fa GitHub博客" href="https://hatboy.github.io/" title="GitHub博客"></a>
                            
                                <a class="fa CSDN" href="http://blog.csdn.net/dj1174232716" title="CSDN"></a>
                            
                        </ul>
                    </nav>
                </section>
                
                
                <section class="switch-part switch-part2">
                    <div class="widget tagcloud" id="js-tagcloud">
                        <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/Cython/">Cython</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Python/">Python</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Python-tips/">Python tips</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Python模块tips/">Python模块tips</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Python语法/">Python语法</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/asyncio/">asyncio</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/异步并发/">异步并发</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/调试/">调试</a></li></ul>
                    </div>
                </section>
                
                
                
                <section class="switch-part switch-part3">
                    <div id="js-friends">
                    
                      <a class="main-nav-link switch-friends-link" href="http://fmxfmx.gitee.io/">FMX</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://jewelz.me/">Jewelz</a>
                    
                      <a class="main-nav-link switch-friends-link" href="https://www.zhihu.com/people/talentisan/activities">轻狂书生</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://threetop.top/">ZCC</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://blog.csdn.net/u012017783">ZCC的CSDN</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://zcc888.gitee.io/">ZCC的博客</a>
                    
                    </div>
                </section>
                

                
                
                <section class="switch-part switch-part4">
                
                    <div id="js-aboutme">一枚爱Python,爱海贼,爱健身,喜欢好玩有趣事物的程序员……</div>
                </section>
                
            </div>
        </div>
    </header>                
</div>
    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
      <div class="overlay">
          <div class="slider-trigger"></div>
          <h1 class="header-author js-mobile-header hide"><a href="/" title="回到主页">HatBoy</a></h1>
      </div>
    <div class="intrude-less">
        <header id="header" class="inner">
            <a href="/" class="profilepic">
                <img src="/img/avatar.jpg" class="animated zoomIn">
            </a>
            <hgroup>
              <h1 class="header-author"><a href="/" title="回到主页">HatBoy</a></h1>
            </hgroup>
            
            <nav class="header-menu">
                <ul>
                
                    <li><a href="/">主页</a></li>
                
                    <li><a href="/archives/">所有文章</a></li>
                
                    <li><a href="/tags/">标签云</a></li>
                
                    <li><a href="/about/">关于我</a></li>
                
                <div class="clearfix"></div>
                </ul>
            </nav>
            <nav class="header-nav">
                        <ul class="social">
                            
                                <a class="fa Email" target="_blank" href="mailto:hatboy-dj@qq.com" title="Email"></a>
                            
                                <a class="fa GitHub" target="_blank" href="https://github.com/HatBoy/" title="GitHub"></a>
                            
                                <a class="fa GitHub博客" target="_blank" href="https://hatboy.github.io/" title="GitHub博客"></a>
                            
                                <a class="fa CSDN" target="_blank" href="http://blog.csdn.net/dj1174232716" title="CSDN"></a>
                            
                        </ul>
            </nav>
        </header>                
    </div>
    <link class="menu-list" tags="标签" friends="友情链接" about="关于我"/>
</nav>
      <div class="body-wrap"><article id="post-第三章-深入Cython" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="/2017/07/17/第三章-深入Cython/" class="article-date">
      <time datetime="2017-07-17T02:31:00.000Z" itemprop="datePublished">2017-07-17</time>
</a>


    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      第三章 深入Cython
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        

        
    <div class="article-tag tagcloud">
        <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Cython/">Cython</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Python/">Python</a></li></ul>
    </div>

        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
        <excerpt in="" index="" |="" 首页摘要="">

<p>深入Cython</p>
<a id="more"></a>
<the rest="" of="" contents="" |="" 余下全文="">


<p>本章主要关注为什么Cython能如此好的加速Python代码，归因于两个不同：</p>
<ul>
<li>1.运行时解释和提前编译</li>
<li>2.动态和静态类型</li>
</ul>
<h2 id="解释和编译后执行"><a href="#解释和编译后执行" class="headerlink" title="解释和编译后执行"></a>解释和编译后执行</h2><p>字节码和机器码的桥梁：Python解释器可以直接运行编译后的C代码，并且对最终用户透明。这些C代码必须编译成特殊类型的动态库，作为扩展模块，这些模块是完整的Python模块，当运行这部分扩展模块的时候，Python虚拟机不在解释字节码，而是直接运行编译后的机器码，这将节省Python解释器的时间开销。<br>这种方式大概能提升Python 10%~30%的性能，但是真正性能改进来自用静态类型替代Python的动态类型。</p>
<h3 id="动态类型和静态类型"><a href="#动态类型和静态类型" class="headerlink" title="动态类型和静态类型"></a>动态类型和静态类型</h3><p>静态类型通过指定变量类型，编译器将基础的操作进行优化，而动态类型获得了灵活性却将大量的时间浪费在了变量类型推断和基础操作中。</p>
<h3 id="静态类型定义关键字：cdef"><a href="#静态类型定义关键字：cdef" class="headerlink" title="静态类型定义关键字：cdef"></a>静态类型定义关键字：cdef</h3><p>使用C语言的变量类型，就要按照C语言的构造规则,<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line">cdef int i, j, k</div><div class="line">cdef float price, margin</div><div class="line"></div><div class="line">cdef int i = <span class="number">0</span></div><div class="line">cdef long int j = <span class="number">0</span>, k = <span class="number">0</span></div><div class="line">cdef float price = <span class="number">0.0</span>, margin = <span class="number">1.0</span></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">integrate</span><span class="params">(a, b, f)</span>:</span></div><div class="line">    cdef int i</div><div class="line">    cdef int N=<span class="number">2000</span></div><div class="line">    cdef float dx, s=<span class="number">0.0</span></div><div class="line">    dx = (b-a)/N</div><div class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(N):</div><div class="line">        s += f(a+i*dx)</div><div class="line">    <span class="keyword">return</span> s * dx</div><div class="line"></div><div class="line"><span class="comment">#也可以使用cdef代码块</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">integrate</span><span class="params">(a, b, f)</span>:</span></div><div class="line">    cdef:</div><div class="line">        int i</div><div class="line">        int N=<span class="number">2000</span></div><div class="line">        float dx, s=<span class="number">0.0</span></div><div class="line">    <span class="comment">#...</span></div></pre></td></tr></table></figure></p>
<p>cdef声明对应表:<br><img src="/2017/07/17/第三章-深入Cython/1.png" alt="cdef声明对应表"></p>
<h3 id="Cython中的自动类型推断"><a href="#Cython中的自动类型推断" class="headerlink" title="Cython中的自动类型推断"></a>Cython中的自动类型推断</h3><p>使用cdef不是Cython的唯一的定义静态变量的方法，Cython还支持自动推断未被定义类型的函数和函数体，默认情况下，Cython只有在不会改变代码语义的情况下才会使用自动类型推断。<br>可以使用infer_types编译指令来给Cython的自动推断更好的控制，infer_types编译指令可以用在函数作用域或者全局作用域，如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">cimport cython</div><div class="line"></div><div class="line"><span class="meta">@cython.infer_types(True)</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">more_inference</span><span class="params">()</span>:</span></div><div class="line">    i = <span class="number">1</span></div><div class="line">    d = <span class="number">2.0</span></div><div class="line">    c = <span class="number">3</span>+<span class="number">4j</span></div><div class="line">    r = i * d + c</div><div class="line">    <span class="keyword">return</span> r</div></pre></td></tr></table></figure></p>
<p>当时用infer_types编译指令的时候，我们应该负责人的确定整数不会溢出，代码语义不会改变，使用它可以很轻易的测试是否改变了代码的结果，以及是否有不同的性能。</p>
<h3 id="Cython中的C指针"><a href="#Cython中的C指针" class="headerlink" title="Cython中的C指针"></a>Cython中的C指针</h3><p>在Cython中，我们可以使用C的语法和语义定义指针，如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">cdef int *p_int</div><div class="line">cdef float** pp_float = NULL</div><div class="line">cdef int *a, *b</div></pre></td></tr></table></figure></p>
<p>由于Python中有<em>和*</em>语法，所以Cython中指针的引用跟C语言中的语法有些不同，有下面两种引用方式：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">cdef double golden_ratio</div><div class="line">cdef double *p_double</div><div class="line">p_double = &amp;golden_ratio</div><div class="line"></div><div class="line"><span class="comment">#下面方式不常用</span></div><div class="line"><span class="keyword">from</span> cython cimport operator</div><div class="line"><span class="keyword">print</span> operator.dereference(p_double)</div></pre></td></tr></table></figure></p>
<p>另外，Cython中指针指向结构体和C语言中也不同：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#C语言用法：</span></div><div class="line">st_t *p_st = make_struct();</div><div class="line">int a_doubled = p_st-&gt;a + p_st-&gt;a;</div><div class="line"></div><div class="line"><span class="comment">#Cython用法：</span></div><div class="line">cdef st_t *p_st = make_struct()</div><div class="line">cdef int a_doubled = p_st.a + p_st.a</div></pre></td></tr></table></figure></p>
<h3 id="混合静态和动态类型变量"><a href="#混合静态和动态类型变量" class="headerlink" title="混合静态和动态类型变量"></a>混合静态和动态类型变量</h3><p>Cython允许静态类型和动态类型变量之间的赋值，如下面例子：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#今天的int类型</span></div><div class="line">cdef int a, b, c</div><div class="line"><span class="comment">#动态元祖类型</span></div><div class="line">tuple_of_ints = (a, b, c)</div></pre></td></tr></table></figure></p>
<p>这个简单的例子能运行是因为C语言中的int和Python中的int有明显的对应关系，如果a,b,c变量是指针，那么这个例子就不能工作，需要先将指针的应用内容放入元祖中或者采用其他策略。<br>下面是C/C++和Python的类型对应关系表:<br><img src="/2017/07/17/第三章-深入Cython/2.png" alt="C/C++和Python的类型对应关系表"></p>
<h3 id="int类型转换和溢出"><a href="#int类型转换和溢出" class="headerlink" title="int类型转换和溢出"></a>int类型转换和溢出</h3><p>注意：int类型的转换需要考虑整数溢出的问题，如果C类型不能代表Python的整数，运行时将会抛出OverflowError异常，我们可以设置overflowcheck和overflowcheck.fold编译指令来捕捉溢出错误</p>
<h3 id="str和unicode类型"><a href="#str和unicode类型" class="headerlink" title="str和unicode类型"></a>str和unicode类型</h3><p>str或unicode的类型转换到char *或std::string类型需要设置c_string_type和c_string_encoding编译指令。</p>
<h3 id="用Python类型声明静态变量"><a href="#用Python类型声明静态变量" class="headerlink" title="用Python类型声明静态变量"></a>用Python类型声明静态变量</h3><p>目前为止，我们已经使用cdef关键字声明C类型的静态变量，他也能够声明Python类型的静态变量，我们可以使用内置的变量类型，如list，tuple，dict，扩展的类型，如NumPy的arrays类型，和其他的许多类型。<br>但并不是所有的Python类型都能被静态声明：他们必须用C语言实现，而且Cython能访问他们的声明。Python内置的类型已经满足这些要求，静态声明他们很简单，如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">cdef list particles, modified_particles</div><div class="line">cdef dict names_from_particles</div><div class="line">cdef str pname</div><div class="line">cdef set unique_particles</div></pre></td></tr></table></figure></p>
<p>在底层，Cython使用C指针指向他们Python内置的结构体类型声明，他们能像普通的Python类型一样使用，但是仅限于他们声明的类型。<br>注意：C语言和Python的除法和取模语义不一样，会有不同的计算行为。默认情况下Cython使用Python的语法语义来计算除法和取模，当然可以使用cdivision编译指令来改变这一行为。</p>
<h3 id="静态类型对加速的意义"><a href="#静态类型对加速的意义" class="headerlink" title="静态类型对加速的意义"></a>静态类型对加速的意义</h3><p>Cython的一般原理：我们提供的静态信息类型越多，Cython优化的结果就越好。<br>Cython目前支持下面一些Python内置的类型静态声明：</p>
<ul>
<li>type, object</li>
<li>bool</li>
<li>complex</li>
<li>basestring, str, unicode, bytes, bytearray</li>
<li>list, tuple, dict, set, frozenset</li>
<li>array</li>
<li>slice</li>
<li>date, time, datetime, timedelta, tzinfo<br>更多的类型支持可能会在未来的版本实现。<br>Python有一个PyLongObjects的C级别的对象来表示任意大小的整数，Cython提供了一个适当的语言无关的方法转换C的整数和Python的整数类型，在转换过程中不可能抛出OverflowError异常。</li>
</ul>
<h3 id="引用计数和静态字符串类型"><a href="#引用计数和静态字符串类型" class="headerlink" title="引用计数和静态字符串类型"></a>引用计数和静态字符串类型</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#这种赋值方式会报错</span></div><div class="line">b1 = <span class="string">b"All men are mortal."</span></div><div class="line">b2 = <span class="string">b"Socrates is a man."</span></div><div class="line">cdef char *buf = b1 + b2</div><div class="line"></div><div class="line"><span class="comment">#下面两种才行</span></div><div class="line">tmp = s1 + s2</div><div class="line">cdef char *buf = tmp</div><div class="line"></div><div class="line">cdef bytes tmp = s1 + s2</div><div class="line">cdef char *buf = tmp</div></pre></td></tr></table></figure>
<h2 id="Cython的三种类型函数"><a href="#Cython的三种类型函数" class="headerlink" title="Cython的三种类型函数"></a>Cython的三种类型函数</h2><p>Python的函数比C语言的函数要灵活强大的多，但是代价是比C语言慢很多，Cython支持同一个文件内C语言的函数和Python的函数相互调用。</p>
<h3 id="Cython中的Python函数用def关键字"><a href="#Cython中的Python函数用def关键字" class="headerlink" title="Cython中的Python函数用def关键字"></a>Cython中的Python函数用def关键字</h3><p>Cython中支持使用def关键字定义Python类型的函数，而且跟在Python的使用一样</p>
<h3 id="Cython中的C类型函数使用cdef关键字"><a href="#Cython中的C类型函数使用cdef关键字" class="headerlink" title="Cython中的C类型函数使用cdef关键字"></a>Cython中的C类型函数使用cdef关键字</h3><p>使用cdef关键字定义C语言类型的函数，参数和返回值都是静态类型，可以使用指针，结构体和其他C语言类型，而不会自动转到Python类型，但是却是Python语法风格如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">cdef long c_fact(long n):</div><div class="line">    <span class="string">"""Computes n!"""</span></div><div class="line">    <span class="keyword">if</span> n &lt;= <span class="number">1</span>:</div><div class="line">        <span class="keyword">return</span> <span class="number">1</span></div><div class="line">    <span class="keyword">return</span> n * c_fact(n - <span class="number">1</span>)</div></pre></td></tr></table></figure></p>
<p>cdef函数在同一个源文件中可以被任何def和cdef函数调用，但是cdef函数不允许被外部的Python代码调用，由于这个限制，cdef函数通常用来作为快速辅助来帮助def函数完成任务。<br>如果我们想要在外部的Python代码使用cdef函数，我们需要用def函数包装cdef函数，如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">wrap_c_fact</span><span class="params">(n)</span>:</span></div><div class="line">    <span class="string">"""Computes n!"""</span></div><div class="line">    <span class="keyword">return</span> c_fact(n)</div></pre></td></tr></table></figure></p>
<h3 id="使用cpdef结合def和cdef函数"><a href="#使用cpdef结合def和cdef函数" class="headerlink" title="使用cpdef结合def和cdef函数"></a>使用cpdef结合def和cdef函数</h3><p>cpdef函数结合了def和def函数的特点，解决了他们的很多局限性，cpdef结合了def的可访问性和cdef的高效性，如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">cpdef long cp_fact(long n):</div><div class="line">    <span class="string">"""Computes n!"""</span></div><div class="line">    <span class="keyword">if</span> n &lt;= <span class="number">1</span>:</div><div class="line">        <span class="keyword">return</span> <span class="number">1</span></div><div class="line">    <span class="keyword">return</span> n * cp_fact(n - <span class="number">1</span>)</div></pre></td></tr></table></figure></p>
<p>cpdef有一个限制，由于cpdef肩负着Python和C的双重责任，他的参数和返回值类型必须是Python和C的兼容类型。任何Python类型都可以在C级别被表示，但是并不是所有的C类型都可以在Python中被表示，所以我们不能在cpdef函数中使用void、C指针或者C数组等类型作为返回值或者参数。</p>
<h2 id="函数和异常处理"><a href="#函数和异常处理" class="headerlink" title="函数和异常处理"></a>函数和异常处理</h2><p>def函数返回的是Python类型，如果出现异常，异常能被正确的传播出去，但是cdef和cpdef函数返回的不是Python类型，出现异常会产生警告，异常会被忽略，不会被传播出去，为了传播异常，Cython提供了except子句，允许cdef和cpdef函数产生异常时和他的调用者进行交流。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">cpdef int divide_ints(int i, int j) except? -1:</div><div class="line">    <span class="keyword">return</span> i / j</div></pre></td></tr></table></figure></p>
<p>如果发生异常，函数会返回-1作为检查异常的哨兵，我们不用手动返回-1，Cython会自动处理这个值，这个值是任意的，可以设置成任何整数值.</p>
<h2 id="函数和embedsignature编译指令"><a href="#函数和embedsignature编译指令" class="headerlink" title="函数和embedsignature编译指令"></a>函数和embedsignature编译指令</h2><p>embedsignature编译指令设置为True能帮助生成默认的签名，知道参数名和函数的默认值。</p>
<h2 id="强制类型转换"><a href="#强制类型转换" class="headerlink" title="强制类型转换"></a>强制类型转换</h2><p>Cython中的类型转换规则跟C语言的类型转换规则很像。</p>
<h2 id="声明和使用structs、unions和enums"><a href="#声明和使用structs、unions和enums" class="headerlink" title="声明和使用structs、unions和enums"></a>声明和使用structs、unions和enums</h2><p>Cython也支持声明、创建和使用C语言的struct、union和enum类型。例子如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#C语言中声明struct和union</span></div><div class="line">struct mycpx &#123;</div><div class="line">    int a;</div><div class="line">    float b;</div><div class="line">&#125;;</div><div class="line"></div><div class="line">union uu &#123;</div><div class="line">    int a;</div><div class="line">    short b, c;</div><div class="line">&#125;;</div><div class="line"></div><div class="line"><span class="comment">#Cython中声明struct和union</span></div><div class="line">cdef struct mycpx:</div><div class="line">    float real</div><div class="line">    float imag</div><div class="line"></div><div class="line">cdef union uu:</div><div class="line">    int a</div><div class="line">    short b, c</div></pre></td></tr></table></figure></p>
<p>也可以使用它ctypedef,定义另一种struct或者union的类型别名，然后使用cdef定义使用 ，如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">ctypedef struct mycpx:</div><div class="line">    float real</div><div class="line">    float imag</div><div class="line"></div><div class="line">ctypedef union uu:</div><div class="line">    int a</div><div class="line">    short b, c</div><div class="line"></div><div class="line"><span class="comment">#几种使用方式</span></div><div class="line">cdef mycpx zz</div><div class="line">zz.real = <span class="number">3.1415</span></div><div class="line">zz.imag = <span class="number">-1.0</span></div><div class="line"></div><div class="line">cdef mycpx a = mycpx(<span class="number">3.1415</span>, <span class="number">-1.0</span>)</div><div class="line">cdef mycpx b = mycpx(real=<span class="number">2.718</span>, imag=<span class="number">1.618034</span>)</div><div class="line"></div><div class="line">cdef mycpx zz = &#123;<span class="string">'real'</span>: <span class="number">3.1415</span>, <span class="string">'imag'</span>: <span class="number">-1.0</span>&#125;</div></pre></td></tr></table></figure></p>
<p>嵌套struct的使用<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">cdef struct _inner:</div><div class="line">    int inner_a</div><div class="line"></div><div class="line">cdef struct nested:</div><div class="line">    int outer_a</div><div class="line">    _inner inner</div><div class="line"></div><div class="line">cdef nested n = &#123;<span class="string">'outer_a'</span>: <span class="number">1</span>, <span class="string">'inner'</span>: &#123;<span class="string">'inner_a'</span>: <span class="number">2</span>&#125;&#125;</div></pre></td></tr></table></figure></p>
<p>enum也可以使用ctypedef和cdef关键字声明使用，和struct、union类似，实例：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">cdef enum PRIMARIES:</div><div class="line">    RED = <span class="number">1</span></div><div class="line">    YELLOW = <span class="number">3</span></div><div class="line">    BLUE = <span class="number">5</span></div><div class="line"></div><div class="line">cdef enum SECONDARIES:</div><div class="line">    ORANGE, GREEN, PURPLE</div><div class="line"></div><div class="line"><span class="comment">#匿名enum在定义全局整数常数时很有用</span></div><div class="line">cdef enum:</div><div class="line">    GLOBAL_SEED = <span class="number">37</span></div></pre></td></tr></table></figure></p>
<h2 id="使用ctypedef声明类型别名"><a href="#使用ctypedef声明类型别名" class="headerlink" title="使用ctypedef声明类型别名"></a>使用ctypedef声明类型别名</h2><p>Cython支持ctypedef关键字，他的用法和C语言的typedef声明类似，在和外部代码对接时很有用，下面是一个简单的例子：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">ctypedef double real</div><div class="line">ctypedef long integral</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">displacement</span><span class="params">(real d0, real v0, real a, real t)</span>:</span></div><div class="line">    <span class="string">"""Calculates displacement under constant acceleration."""</span></div><div class="line">    cdef real d = d0 + (v0 * t) + (<span class="number">0.5</span> * a * t**<span class="number">2</span>)</div><div class="line">    <span class="keyword">return</span> d</div></pre></td></tr></table></figure></p>
<p>一个ctypedef声明必须在文件域内，不能再函数域声明。</p>
<h2 id="Cython的for循环和while循环"><a href="#Cython的for循环和while循环" class="headerlink" title="Cython的for循环和while循环"></a>Cython的for循环和while循环</h2><p>Cython支持无改动的Python的for循环和while循环的优化，它能够自推断类型并生成优化代码，但是并不是任何时候都会这样做，比如下面代码，n是动态的类型，Cython将不会进行C语言的加速优化，将n改为静态类型才会进行加速优化<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">n = <span class="number">100</span></div><div class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(n):</div><div class="line">    <span class="comment"># ...</span></div><div class="line"></div><div class="line"><span class="comment">#加速优化</span></div><div class="line">cdef unsigned int i, n = <span class="number">100</span></div><div class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(n):</div><div class="line">    <span class="comment"># ...</span></div></pre></td></tr></table></figure></p>
<h3 id="高效for循环指南"><a href="#高效for循环指南" class="headerlink" title="高效for循环指南"></a>高效for循环指南</h3><p>将循环变量声明为静态类型，Cython会加速优化for循环，但是如果你在循环中对列表进行索引，Cython不会检查索引是否越界。<br>当容器是list, tuple, dict等等类型时，静态的循环索引变量也会带来很大的开销，为了for循环更加高效，可以使用其他的更加高效的容器替换。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">n = len(a) - <span class="number">1</span></div><div class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">1</span>, n):</div><div class="line">    a[i] = (a[i<span class="number">-1</span>] + a[i] + a[i+<span class="number">1</span>]) / <span class="number">3.0</span></div><div class="line"></div><div class="line"><span class="comment">#优化后</span></div><div class="line">cdef unsigned int i, n = len(a) - <span class="number">1</span></div><div class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">1</span>, n):</div><div class="line">    a[i] = (a[i<span class="number">-1</span>] + a[i] + a[i+<span class="number">1</span>]) / <span class="number">3.0</span></div></pre></td></tr></table></figure></p>
<h2 id="Cython预编译"><a href="#Cython预编译" class="headerlink" title="Cython预编译"></a>Cython预编译</h2><p>Cython有一个DEF关键字创建宏，是一个编译时符号，类似于C语言的#define，DEF常数必须在编译时被解析，而且只能是简单类型，它们可以是浮点数、整数或者字符串，如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">DEF E = <span class="number">2.718281828459045</span></div><div class="line">DEF PI = <span class="number">3.141592653589793</span></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">feynmans_jewel</span><span class="params">()</span>:</span></div><div class="line">    <span class="string">"""Returns e**(i*pi) + 1. Should be ~0.0"""</span></div><div class="line">    <span class="keyword">return</span> E ** (<span class="number">1j</span> * PI) + <span class="number">1.0</span></div></pre></td></tr></table></figure></p>
<h2 id="连接Python2和Python3的桥梁"><a href="#连接Python2和Python3的桥梁" class="headerlink" title="连接Python2和Python3的桥梁"></a>连接Python2和Python3的桥梁</h2><p>我们可以用Python2或者Python3语法编写Cython的.pyx文件，生成的C语言代码是兼容Python2和Python3的，也就是说任何Cython代码都能编译成Python2模块或者Python3模块。Cython会自动推断Python版本，也可以使用参数来指定编译版本：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#指定以Python3版本编译</span></div><div class="line">$ cython <span class="number">-3</span> file.pyx</div><div class="line"><span class="comment">#指定以Python2版本编译</span></div><div class="line">$ cython <span class="number">-2</span> file.pyx</div></pre></td></tr></table></figure></p>
</the></excerpt>
      
    </div>
    
  </div>
  
    
    <div class="copyright">
        <p><span>本文标题:</span><a href="/2017/07/17/第三章-深入Cython/">第三章 深入Cython</a></p>
        <p><span>文章作者:</span><a href="/" title="回到主页">HatBoy</a></p>
        <p><span>发布时间:</span>2017-07-17, 10:31:00</p>
        <p><span>最后更新:</span>2017-12-21, 18:08:24</p>
        <p>
            <span>原始链接:</span><a class="post-url" href="/2017/07/17/第三章-深入Cython/" title="第三章 深入Cython">http://hatboy.gitee.io/2017/07/17/第三章-深入Cython/</a>
            <span class="copy-path" data-clipboard-text="原文: http://hatboy.gitee.io/2017/07/17/第三章-深入Cython/　　作者: HatBoy" title="点击复制文章链接"><i class="fa fa-clipboard"></i></span>
            <script> var clipboard = new Clipboard('.copy-path'); </script>
        </p>
        <p>
            <span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/" title="CC BY-NC-SA 4.0 International" target = "_blank">"署名-非商用-相同方式共享 4.0"</a> 转载请保留原文链接及作者。
        </p>
    </div>



    <nav id="article-nav">
        
            <div id="article-nav-newer" class="article-nav-title">
                <a href="/2017/07/31/Python性能分析与调试/">
                    Python性能分析与调试
                </a>
            </div>
        
        
            <div id="article-nav-older" class="article-nav-title">
                <a href="/2017/07/03/第二章-编译和运行Cython代码/">
                    第二章 编译和运行Cython代码
                </a>
            </div>
        
    </nav>

  
</article>

    <div id="toc" class="toc-article">
        <strong class="toc-title">文章目录</strong>
        
            <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#解释和编译后执行"><span class="toc-number">1.</span> <span class="toc-text">解释和编译后执行</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#动态类型和静态类型"><span class="toc-number">1.1.</span> <span class="toc-text">动态类型和静态类型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#静态类型定义关键字：cdef"><span class="toc-number">1.2.</span> <span class="toc-text">静态类型定义关键字：cdef</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Cython中的自动类型推断"><span class="toc-number">1.3.</span> <span class="toc-text">Cython中的自动类型推断</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Cython中的C指针"><span class="toc-number">1.4.</span> <span class="toc-text">Cython中的C指针</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#混合静态和动态类型变量"><span class="toc-number">1.5.</span> <span class="toc-text">混合静态和动态类型变量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#int类型转换和溢出"><span class="toc-number">1.6.</span> <span class="toc-text">int类型转换和溢出</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#str和unicode类型"><span class="toc-number">1.7.</span> <span class="toc-text">str和unicode类型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#用Python类型声明静态变量"><span class="toc-number">1.8.</span> <span class="toc-text">用Python类型声明静态变量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#静态类型对加速的意义"><span class="toc-number">1.9.</span> <span class="toc-text">静态类型对加速的意义</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#引用计数和静态字符串类型"><span class="toc-number">1.10.</span> <span class="toc-text">引用计数和静态字符串类型</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Cython的三种类型函数"><span class="toc-number">2.</span> <span class="toc-text">Cython的三种类型函数</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Cython中的Python函数用def关键字"><span class="toc-number">2.1.</span> <span class="toc-text">Cython中的Python函数用def关键字</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Cython中的C类型函数使用cdef关键字"><span class="toc-number">2.2.</span> <span class="toc-text">Cython中的C类型函数使用cdef关键字</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用cpdef结合def和cdef函数"><span class="toc-number">2.3.</span> <span class="toc-text">使用cpdef结合def和cdef函数</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#函数和异常处理"><span class="toc-number">3.</span> <span class="toc-text">函数和异常处理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#函数和embedsignature编译指令"><span class="toc-number">4.</span> <span class="toc-text">函数和embedsignature编译指令</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#强制类型转换"><span class="toc-number">5.</span> <span class="toc-text">强制类型转换</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#声明和使用structs、unions和enums"><span class="toc-number">6.</span> <span class="toc-text">声明和使用structs、unions和enums</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#使用ctypedef声明类型别名"><span class="toc-number">7.</span> <span class="toc-text">使用ctypedef声明类型别名</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Cython的for循环和while循环"><span class="toc-number">8.</span> <span class="toc-text">Cython的for循环和while循环</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#高效for循环指南"><span class="toc-number">8.1.</span> <span class="toc-text">高效for循环指南</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Cython预编译"><span class="toc-number">9.</span> <span class="toc-text">Cython预编译</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#连接Python2和Python3的桥梁"><span class="toc-number">10.</span> <span class="toc-text">连接Python2和Python3的桥梁</span></a></li></ol>
        
    </div>
    <style>
        .left-col .switch-btn,
        .left-col .switch-area {
            display: none;
        }
        .toc-level-3 i,
        .toc-level-3 ol {
            display: none !important;
        }
    </style>

    <input type="button" id="tocButton" value="隐藏目录"  title="点击按钮隐藏或者显示文章目录">

    <script>
        yiliaConfig.toc = ["隐藏目录", "显示目录", !!"false"];
    </script>



    
<div class="share">
    
        <div class="bdsharebuttonbox">
            <a href="#" class="fa fa-twitter bds_twi" data-cmd="twi" title="分享到推特"></a>
            <a href="#" class="fa fa-weibo bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
            <a href="#" class="fa fa-qq bds_sqq" data-cmd="sqq" title="分享给 QQ 好友"></a>
            <a href="#" class="fa fa-files-o bds_copy" data-cmd="copy" title="复制网址"></a>
            <a href="#" class="fa fa fa-envelope-o bds_mail" data-cmd="mail" title="通过邮件分享"></a>
            <a href="#" class="fa fa-weixin bds_weixin" data-cmd="weixin" title="生成文章二维码"></a>
            <a href="#" class="fa fa-share-alt bds_more" data-cmd="more"></i></a>
        </div>
        <script>
            window._bd_share_config={
                "common":{"bdSnsKey":{},"bdText":"第三章 深入Cython　| HatBoy的个人主页　","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"24"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
        </script>
    

    
</div>







    




    <div class="scroll" id="post-nav-button">
        
            <a href="/2017/07/31/Python性能分析与调试/" title="上一篇: Python性能分析与调试">
                <i class="fa fa-angle-left"></i>
            </a>
        

        <a title="文章列表"><i class="fa fa-bars"></i><i class="fa fa-times"></i></a>

        
            <a href="/2017/07/03/第二章-编译和运行Cython代码/" title="下一篇: 第二章 编译和运行Cython代码">
                <i class="fa fa-angle-right"></i>
            </a>
        
    </div>

    <ul class="post-list"><li class="post-list-item"><a class="post-list-link" href="/2018/02/27/如何恢复丢失的Python源代码如果它还在内存中运行/">如何恢复丢失的Python源代码如果它还在内存中运行</a></li><li class="post-list-item"><a class="post-list-link" href="/2018/02/08/pathlib：文件系统路径作为对象/">pathlib：文件系统路径作为对象</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio：异步IO、事件循环和并发/">asyncio：异步IO、事件循环和并发</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之调试asyncio/">asyncio之调试asyncio</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之协程结合线程和进程/">asyncio之协程结合线程和进程</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之接收Unix信号/">asyncio之接收Unix信号</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之使用子进程/">asyncio之使用子进程</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之与DNS服务进行交互/">asyncio之与DNS服务进行交互</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之使用SSL/">asyncio之使用SSL</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之使用协程和流的异步I-O/">asyncio之使用协程和流的异步I/O</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之协议抽象类的异步I-O/">asyncio之协议抽象类的异步I/O</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之同步原语/">asyncio之同步原语</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之用控制结构组建协程/">asyncio之用控制结构组建协程</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之并发执行Tasks/">asyncio之并发执行Tasks</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之异步生产结果/">asyncio之异步生产结果</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之定时调度常规函数/">asyncio之定时调度常规函数</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之使用协程处理多任务/">asyncio之使用协程处理多任务</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之异步并发的概念/">asyncio之异步并发的概念</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/Python上下文管理器/">Python上下文管理器</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/Python-importlib讲解/">Python importlib讲解</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/第七章-用Cython包装C库/">第七章 用Cython包装C库</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/08/16/第六章-组织Cython代码/">第六章 组织Cython代码</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/08/10/第五章-Cython和扩展类型/">第五章 Cython和扩展类型</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/07/31/第四章-Cython实践：N-body模拟/">第四章 Cython实践：N-body模拟</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/07/31/Python性能分析与调试/">Python性能分析与调试</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/07/17/第三章-深入Cython/">第三章 深入Cython</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/07/03/第二章-编译和运行Cython代码/">第二章 编译和运行Cython代码</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/07/02/第一章-Cython简介/">第一章 Cython简介</a></li></ul>




    <script>
        
    </script>
</div>
      <footer id="footer">
    <div class="outer">
        <div id="footer-info">
            <div class="footer-left">
                <i class="fa fa-copyright"></i> 
                2017-2018 HatBoy
            </div>
            <div class="footer-right">
                <a href="http://hexo.io/" target="_blank" title="快速、简洁且高效的博客框架">Hexo</a>  Theme <a href="https://github.com/MOxFIVE/hexo-theme-yelee" target="_blank" title="简而不减 Hexo 双栏博客主题  v3.5">Yelee</a> by MOxFIVE <i class="fa fa-heart animated infinite pulse"></i>
            </div>
        </div>
        
            <div class="visit">
                
                    <span id="busuanzi_container_site_pv" style='display:none'>
                        <span id="site-visit" title="本站到访数"><i class="fa fa-user" aria-hidden="true"></i><span id="busuanzi_value_site_uv"></span>
                        </span>
                    </span>
                
                
                    <span>| </span>
                
                
                    <span id="busuanzi_container_page_pv" style='display:none'>
                        <span id="page-visit"  title="本页阅读量"><i class="fa fa-eye animated infinite pulse" aria-hidden="true"></i><span id="busuanzi_value_page_pv"></span>
                        </span>
                    </span>
                
            </div>
        
    </div>
</footer>
    </div>
    
<script data-main="/js/main.js" src="//cdn.bootcss.com/require.js/2.2.0/require.min.js"></script>





    <script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script src="//cdn.bootcss.com/mathjax/2.6.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


<div class="scroll" id="scroll">
    <a href="#" title="返回顶部"><i class="fa fa-arrow-up"></i></a>
    <a href="#comments" onclick="load$hide();" title="查看评论"><i class="fa fa-comments-o"></i></a>
    <a href="#footer" title="转到底部"><i class="fa fa-arrow-down"></i></a>
</div>
<script>
    // Open in New Window
    
        $("a").attr("target", "_blank");
        $("#scroll a, #toc a").removeAttr("target");
    
</script>

<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  </div>
</body>
</html>